<template>
	<div class="player">
		<img @click="togglePlay" src="@/assets/images/listening/icon-play.png" />
		<audio ref="audio" @timeupdate="updateProgress" @loadedmetadata="setDuration">
			<source type="audio/mpeg" src="" />
		</audio>
		<div class="progress-container" @click="seek($event)">
			<div class="progress-bar" :style="{ width: progress + '%' }"></div>
			<div class="progress-ball" :style="{ left: progress + '%' }"></div>
		</div>
		<div class="time">
			{{ formatTime(currentTime) }} / {{ formatTime(duration) }}
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		watch,
		defineProps
	} from "vue";

	const props = defineProps(["audioSrc"]);

	const audio = ref(null);
	const isPlaying = ref(false);
	const currentTime = ref(0);
	const duration = ref(0);
	const progress = ref(0);

	const togglePlay = () => {
		if (audio.value.paused) {
			audio.value.play();
			isPlaying.value = true;
		} else {
			audio.value.pause();
			isPlaying.value = false;
		}
	};

	const formatTime = (value) => {
		const minutes = Math.floor(value / 60);
		const seconds = Math.floor(value % 60);
		return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
	};

	const updateProgress = () => {
		currentTime.value = audio.value.currentTime;
		progress.value = (currentTime.value / duration.value) * 100;
	};

	const setDuration = () => {
		duration.value = audio.value.duration;
	};

	const seek = (event) => {
		const progressContainer = event.currentTarget;
		const rect = progressContainer.getBoundingClientRect();
		const offsetX = event.clientX - rect.left;
		const newTime = (offsetX / rect.width) * duration.value;
		audio.value.currentTime = newTime;
	};

	onMounted(() => {
		audio.value.addEventListener("timeupdate", updateProgress);
		audio.value.addEventListener("loadedmetadata", setDuration);
	});

	// onUnmounted(() => {
	//   audio.value.removeEventListener("timeupdate", updateProgress);
	//   audio.value.removeEventListener("loadedmetadata", setDuration);
	// });
</script>

<style lang="scss" scoped>
	.player {
		display: flex;
		align-items: center;

		img {
			width: 18px;
			height: 18px;
			margin-right: 10px;
		}

		.progress-container {
			width: 100%;
			background: #f5f5f5;
			border-radius: 4px;
			cursor: pointer;
			height: 6px;
			position: relative;

			.progress-bar {
				height: 100%;
				background-color: #58d15c;
				border-radius: 4px;
			}

			.progress-ball {
				position: absolute;
				top: 50%;
				width: 10px;
				height: 10px;
				background-color: #4caf50;
				border-radius: 50%;
				transform: translate(-50%, -50%);
			}
		}

		.time {
			font-size: 12px;
			color: #8e8e8e;
			width: 100px;
			margin-left: 10px;
		}
	}
</style>